package com.sport.interceptor;

import com.google.gson.Gson;
import com.sport.constant.JwtClaimsConstant;
import com.sport.context.BaseContext;
import com.sport.pojo.entity.DoubleToken;
import com.sport.properties.JwtProperties;
import com.sport.result.Result;
import com.sport.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        response.setContentType("text/html;charset=utf-8");
        String shortToken = request.getHeader("shortToken");
        String longToken = request.getHeader("longToken");

        //2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), shortToken);
            BaseContext.setCurrentId(claims.get("userId").toString());
            log.info("当前用户ID:"+claims.get("userId").toString());
            //System.out.println("当前用户ID:"+claims.get("userId").toString());
            return true;
        } catch (Exception ex) {
            //response.setStatus(401);
            log.info("shortToken过期");
        }
        //return false;

        try {
            log.info("校验长token");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), longToken);
            log.info("当前用户ID:"+claims.get("userId").toString());
            String shortJwt = JwtUtil.createJWT(jwtProperties.getSecretKey(),
                    jwtProperties.getShortTK(),
                    claims);
            String LongJwt = JwtUtil.createJWT(jwtProperties.getSecretKey(),
                    jwtProperties.getLongTK(),
                    claims);
            //System.out.println(shortJwt + longToken);
            String token = new Gson().toJson(new DoubleToken(shortJwt, LongJwt,null));
            response.setStatus(401);
            response.getWriter().write(new Gson().toJson(Result.tokenError(401,"longToken未过期",token)));
            return false;
        } catch (Exception ex1) {
            log.info("longToken过期");
            response.getWriter().write(new Gson().toJson(Result.tokenError(402,"longToken过期","双token过期")));
        }
        return false;


    }
}
